/**
 * 
 */
package com.nextive.interview.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.Context;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.RawContacts;
import android.provider.ContactsContract.RawContactsEntity;
import android.util.Log;

import com.nextive.interview.dto.ContactDetails;

/**
 * @author Cesar Roman
 *
 */
public class PhoneContactsUtil {
	
	private static final String TAG = "PhoneContactsUtil";
	
	public static List<ContactDetails> generatePhoneContactsEmailArray(Context context) {
		
		ContentResolver contentResolver = context.getContentResolver();
		
		// First look up all contacts with their emails
		Cursor rawContactsEntityCursor = contentResolver.query(RawContactsEntity.CONTENT_URI, 
				new String[] { 
				RawContactsEntity.MIMETYPE,
				RawContactsEntity.DATA1,
				RawContactsEntity.CONTACT_ID }, null, null, null);
		
		Map<String, String> mapIdEmail = new HashMap<String, String>();
		try {
			
			String dataType;
			while (rawContactsEntityCursor.moveToNext()) {
				
				dataType = rawContactsEntityCursor.getString(0);
				if (dataType != null && Email.CONTENT_ITEM_TYPE.equals(dataType)) {
					
					// add pair id - email
					mapIdEmail.put(rawContactsEntityCursor.getString(2), rawContactsEntityCursor.getString(1));
					
				}
			}
			
		} finally {
			rawContactsEntityCursor.close();
		}
		
		// Once we have all contacts id which have emails then go look for contact names
//		Cursor rawContactsCursor = contentResolver.query(RawContacts.CONTENT_URI, 
//				new String[] { 
//				RawContacts.CONTACT_ID,
//				RawContacts.DISPLAY_NAME_PRIMARY }, null, null, null);
		Cursor rawContactsCursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, 
				new String[] { 
				ContactsContract.Contacts._ID,
				ContactsContract.Contacts.DISPLAY_NAME }, null, null, null);

		List<ContactDetails> resultList = new ArrayList<ContactDetails>();
		try {
			
			String contactId;
			while (rawContactsCursor.moveToNext()) {
				
				contactId = rawContactsCursor.getString(0);
				if (contactId != null && mapIdEmail.containsKey(contactId)) {
					
					// add pair id - email
					//resultList.add(buildDisplayEmail(mapIdEmail.get(contactId), rawContactsCursor.getString(1)));
					resultList.add(new ContactDetails(rawContactsCursor.getString(1), mapIdEmail.get(contactId)));
					
				}
			}
			
		} finally {
			rawContactsCursor.close();
		}
		
		return resultList;
		
	}
	
	public static boolean createNewPhoneContactBatch(Context context, String name, String email) {
		
		try {

			ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();
			
			int rawContactCreatedIndex = 0;
			
			operations.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
					.withValue(RawContacts.ACCOUNT_NAME, /*"SIM"*/null)
					.withValue(RawContacts.ACCOUNT_TYPE, /*"con.android.contacts.sim"*/null)
					.build());

			operations.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
					.withValueBackReference(Data.RAW_CONTACT_ID, rawContactCreatedIndex)
					.withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)
					.withValue(StructuredName.GIVEN_NAME, name)
					.build());
			
			operations.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
					.withValueBackReference(Data.RAW_CONTACT_ID, rawContactCreatedIndex)
					.withValue(Data.MIMETYPE, Email.CONTENT_ITEM_TYPE)
					.withValue(Data.DATA1, email)
					.withValue(Data.DATA2, new String(name + "( " + email + " )"))
					.build());
	
			context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, operations);
			return true;
			
		} catch (RemoteException e) {
			
			Log.e(TAG, "Unable to create new contact. RemoteException.", e);
			e.printStackTrace();
			return false;
			
		} catch (OperationApplicationException e) {

			Log.e(TAG, "Unable to create new contact. OperationApplicationException.", e);
			e.printStackTrace();
			return false;
			
		}
		
	}

//	private static final String buildDisplayEmail(String email, String displayName) {
//		
//		return displayName + " ( " + email + " )";
//		
//	}

}
